package biz.datalk.industrialland.common.validated.validator;

import biz.datalk.industrialland.common.validated.IdCard;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @author tarofang@163.com
 * @date 2019-08-19
 */
@Slf4j
public class IdCardValidator implements ConstraintValidator<IdCard, String> {
    private String message;
    private String blankMessage;

    @Override
    public void initialize(IdCard constraintAnnotation) {
        message = constraintAnnotation.message();
        blankMessage = constraintAnnotation.blankMessage();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (StringUtils.isBlank(value)) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(blankMessage).addConstraintViolation();
            return Boolean.FALSE;
        }

        // 验证长度
        int len = StringUtils.length(value);
        if (len != 18 && len != 15) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(message).addConstraintViolation();
            log.warn("IdCard length wrong. [len={}]", len);
            return Boolean.FALSE;
        }

        // 身份证内容为 数字+x
        boolean matches = value.matches("^(\\d{14}[0-9xX])|(\\d{17}[0-9xX])$");
        if (matches) {
            log.debug("IdCard match success. [matchResult={}]", matches);
        } else {
            log.warn("IdCard match wrong. [matchResult={}, value={}]", matches, value);
        }
        return matches;
    }

}
